package com.laundry.service.impl;

import com.laundry.dao.MessageDao;
import com.laundry.dto.ResultDTO;
import com.laundry.entity.Message;
import com.laundry.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageDao messageDao;

    @Override
    public ResultDTO getMessages(Long userId) {
        try {
            List<Message> messages = messageDao.findByUserIdOrderByCreateTimeDesc(userId);
            System.out.println("查询到的消息数量: " + (messages != null ? messages.size() : 0)); // 调试信息
            return ResultDTO.success(messages);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDTO.error("获取消息列表失败: " + e.getMessage());
        }
    }

    @Override
    public ResultDTO getUnreadCount(Long userId) {
        try {
            int count = messageDao.countByUserIdAndReadStatus(userId, 0);
            System.out.println("未读消息数量: " + count); // 调试信息
            return ResultDTO.success(count);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDTO.error("获取未读消息数量失败: " + e.getMessage());
        }
    }

    @Override
    public ResultDTO readMessage(Long messageId) {
        try {
            Message message = messageDao.findById(messageId).orElse(null);
            if (message == null) {
                return ResultDTO.error("消息不存在");
            }
            
            message.setReadStatus(1);
            message.setUpdateTime(new Date());
            messageDao.save(message);
            
            return ResultDTO.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDTO.error("标记已读失败: " + e.getMessage());
        }
    }

    @Override
    public ResultDTO sendMessage(Long userId, String title, String content) {
        try {
            System.out.println("发送消息: 用户ID=" + userId + ", 标题=" + title); // 调试信息
            
            Message message = new Message();
            message.setUserId(userId);
            message.setTitle(title);
            message.setContent(content);
            message.setReadStatus(0);
            message.setCreateTime(new Date());
            
            messageDao.save(message);
            System.out.println("消息已保存, ID: " + message.getId()); // 调试信息
            
            return ResultDTO.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDTO.error("发送消息失败: " + e.getMessage());
        }
    }
} 